<template>
    <el-drawer :model-value="drawer" direction="rtl" :before-close="handleClose">
      <template #header>
        <h4>编辑轮播图</h4>
      </template>
      <template #default>
        <el-form :model="newBanner" label-width="auto" style="max-width: 600px">
          <el-form-item label="图片地址">
            <el-input v-model="newBanner.img" />
          </el-form-item>
          <el-form-item label="图片连接">
            <el-input v-model="newBanner.link" />
          </el-form-item>
          <el-form-item label="图片提示">
            <el-input v-model="newBanner.alt" />
          </el-form-item>
          <el-form-item label="是否启用">
            <el-switch v-model="newBanner.flag" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editBanner">修改</el-button>
            <el-button @click="cancelFn">取消</el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-drawer>
  </template>
  
  <script lang="ts" setup>
  import { defineProps, withDefaults, reactive, watch } from "vue";
  import { ElMessage } from "element-plus";
  import { getBannerListApi, updateBannerFlagApi } from "@/api/banners";
  import type { IBanner } from "@/myTypes";
  
  const props = withDefaults(
    defineProps<{
      drawer: boolean;
      bannerid: string;
    }>(),
    {
      drawer: false,
    }
  );
  
  const emit = defineEmits<{
    (e: "hideMe"): void;
    (e: "modified"): void;
  }>();
  
  // 取消按钮
  const cancelFn = () => {
    emit("hideMe");
  };
  
  // 关闭按钮
  const handleClose = () => {
    emit("hideMe");
  };
  
  const newBanner = reactive<IBanner>({
    img: "",
    link: "",
    alt: "",
    flag: false,
  });
  
  // 初始化数据：
  const initBanner = async () => {
    console.log("initBanner");
    // props.bannerid;
    const res = await getBannerListApi();
    if (res.data.code === "200") {
      let obj = res.data.data.filter(
        (item: IBanner) => item.bannerid == props.bannerid
      )[0];
      newBanner.img = obj.img;
      newBanner.link = obj.link;
      newBanner.alt = obj.alt;
      newBanner.flag = obj.flag;
    }
  };
  
  watch(props, initBanner);
  
  // 修改
  const editBanner = async () => {
    const res = await updateBannerFlagApi(
      props.bannerid,
      newBanner.flag as boolean
    );
    if (res.data.code === "200") {
      ElMessage.success("修改成功！");
      emit("modified");
    }
  };
  
  </script>
  